//
//  MyCenterViewController.m
//  InviteJob
//
//  Created by chirui on 2017/10/13.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "MyCenterViewController.h"
#import "MyWalletDetailVC.h"
#import "MessageVC.h"
#import "SetViewController.h"
#import "HRViewController.h"
#import "MyResumeListViewController.h"
#import "LoginViewController.h"//登录
#import "MyInformationViewController.h"
#import "CertificationViewController.h"

#import "MyCollectListViewController.h"
#import "MyLookListViewController.h"
#import "MyReceivedViewController.h"
#import "MyBuyViewController.h"

#import <WXApi.h>

@interface MyCenterViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate> {
    
    UIButton *_buttonShare;
    
    NSString *_isMsgStatus;
    
}
@property (nonatomic, strong) UIButton *navRightButton;

@property (nonatomic, strong) UITableView * tableView;

@property (nonatomic, strong) NSMutableArray *dataMsg;


@end
@implementation MyCenterViewController


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    isUser
    if (user.user_id) {
        [self postDataNoStatus];
    }
    
    [self creatTableView];
    
}

-(NSMutableArray *)dataMsg{
    if (!_dataMsg) {
        _dataMsg = @[].mutableCopy;
    }
    return _dataMsg;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    TitleView(@"我的");
    self.view.backgroundColor =[UIColor whiteColor];
    
    // right item
    self.navRightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [self.navRightButton setImage:[UIImage imageNamed:@"icon_user_list_shar"] forState:UIControlStateNormal];
    self.navRightButton.imageEdgeInsets = UIEdgeInsetsMake(0,15, 0, -15);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.navRightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    // 事件绑定
    [self.navRightButton addTarget:self action:@selector(navAction) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)navAction {
    
    isUser
    
    if (!user.user_id) {
       
        LoginViewController *login = [LoginViewController new];
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
        
        return;
    }
    
    _buttonShare = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    _buttonShare.backgroundColor = [UIColor colorWithColor:[UIColor blackColor] alpha:0.4];
    [_buttonShare addTarget:self action:@selector(OnClickCase) forControlEvents:UIControlEventTouchUpInside];
    UIWindow * window = [self lastWindow];
    [window addSubview:_buttonShare];
    
    
    //背景View
    UIView *viewbg = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT-130, WIDTH, 130)];
    viewbg.backgroundColor = [UIColor whiteColor];
    [_buttonShare addSubview:viewbg];
    
 
    UIView *viewLabel = [[UIView alloc] initWithFrame:CGRectMake(30, 30, WIDTH-60, 1)];
    viewLabel.backgroundColor = strColor(@"f6f6f6");
    [viewbg addSubview:viewLabel];
    UILabel *labelMsg = [[UILabel alloc] init];
    labelMsg.font = [UIFont systemFontOfSize:15];
    labelMsg.backgroundColor = [UIColor whiteColor];
    labelMsg.textAlignment = NSTextAlignmentCenter;
    labelMsg.textColor = strColor(@"999");
    labelMsg.text = @"分享到";
    [viewbg addSubview:labelMsg];
    [labelMsg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(viewbg);
        make.top.equalTo(@22);
        make.height.equalTo(@15);
        make.width.equalTo(@80);
    }];
    
    NSArray * array = @[@"icon_wallet_wechat",@"icon_share_friends"];
    NSArray * titleArray = @[@"微信好友",@"朋友圈"];
    for (int i = 0; i < 2; i ++) {
        UIButton *_kindBtnfour = [UIButton buttonWithType:UIButtonTypeCustom];
        [viewbg addSubview:_kindBtnfour];
        _kindBtnfour.tag = 1000+i;
        [_kindBtnfour addTarget:self action:@selector(OnShareClik:) forControlEvents:UIControlEventTouchUpInside];
        [_kindBtnfour mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(viewbg.mas_bottom);
            make.left.mas_equalTo(WIDTH/2*i+5);
            make.size.mas_equalTo(CGSizeMake(WIDTH/2-10, 85));
        }];
        UIImageView *kindImages = [UIImageView new];
        kindImages.image = [UIImage imageNamed:array[i]];
        kindImages.layer.cornerRadius = 19;
        kindImages.clipsToBounds = YES;
        [_kindBtnfour addSubview:kindImages];
        [kindImages mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@10);
            make.centerX.mas_equalTo(_kindBtnfour);
            make.size.mas_equalTo(CGSizeMake(38, 38));
        }];
        
        UILabel *kindlabels = [UILabel new];
        kindlabels.text = titleArray[i];
        kindlabels.font = [UIFont systemFontOfSize:13];
        kindlabels.textColor = strColor(@"333");
        kindlabels.textAlignment = NSTextAlignmentCenter;
        [_kindBtnfour addSubview:kindlabels];
        [kindlabels mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(kindImages.mas_bottom).with.mas_offset(5);
            make.centerX.mas_equalTo(_kindBtnfour);
            make.size.mas_equalTo(CGSizeMake(WIDTH/2-10, 20));
        }];
    }
}
-(void)OnShareClik:(UIButton *)sender{
    
    isUser
    
    NSDictionary *dic = @{@"user_id":user.user_id};
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(share_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            if (sender.tag == 1000) {
                WXMediaMessage *message = [WXMediaMessage message];
                message.title = responseObject[@"datas"][@"title"];
                message.description = responseObject[@"datas"][@"content"];
                
                [message setThumbImage: [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString: responseObject[@"datas"][@"image"]]]]];
                
                WXWebpageObject *webpageObject = [WXWebpageObject object];
                webpageObject.webpageUrl = responseObject[@"datas"][@"url"];
                message.mediaObject = webpageObject;
                
                SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                req.bText = NO;
                req.message = message;
                req.scene = WXSceneSession;
                
                [WXApi sendReq:req];
                
            }
            
            if (sender.tag == 1001) {
                WXMediaMessage *message = [WXMediaMessage message];
                message.title = responseObject[@"datas"][@"title"];
                message.description = responseObject[@"datas"][@"content"];
                
                [message setThumbImage:[UIImage imageNamed:@""]];
                
                WXWebpageObject *webpageObject = [WXWebpageObject object];
                webpageObject.webpageUrl = responseObject[@"datas"][@"url"];
                message.mediaObject = webpageObject;
                
                SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
                req.bText = NO;
                req.message = message;
                req.scene = WXSceneTimeline;
                
                [WXApi sendReq:req];
            }
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
    
}
-(void)OnClickCase{
    [_buttonShare removeFromSuperview];
}
#pragma mark - 事件响应
- (UIWindow *)lastWindow
{
    NSArray *windows = [UIApplication sharedApplication].windows;
    for(UIWindow *window in [windows reverseObjectEnumerator]) {
        if ([window isKindOfClass:[UIWindow class]] &&
            CGRectEqualToRect(window.bounds, [UIScreen mainScreen].bounds))
            return window;}
    return [UIApplication sharedApplication].keyWindow;
}
-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, -64, WIDTH, HEIGHT-50) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = strColor(@"f6f6f6");
    _tableView.separatorColor = strColor(@"e5e5e5");
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.dataSource = self;
     _tableView.delegate = self;

    
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_tableView.contentOffset.y <= 0) {
        _tableView.bounces = NO;
    }
    else
        if (_tableView.contentOffset.y >= 0){
            _tableView.bounces = YES;
        }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section==0) {
        return 5;
    }
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==0) {
        return 280;
    }
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray * array = @[@"企业/团队认证",@"我要招人",@"已购简历",@"已看简历",@"已收简历",@"设置"];
    NSArray * imageArray = @[@"icon_user_info",@"icon_user_recruit_talents",@"icon_user_recruit_purchase",@"icon_user_view_resume",@"icon_user_resume_received",@"icon_user_Set_up"];
    static  NSString * str = @"cellid";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell==nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }else {
        while ([cell.contentView.subviews lastObject]!=nil) {
            
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font =[UIFont systemFontOfSize:15];
    if (indexPath.section==0) {
        cell.imageView.image = ImageName(imageArray[indexPath.row]);
        cell.textLabel.text = array[indexPath.row];
    }else{
        cell.imageView.image = ImageName(imageArray[5]);
        cell.textLabel.text = array[5];
        
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView * heardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 280)];
    heardView.backgroundColor = strColor(@"f6f6f6");
    
    if (section==0) {
        UIImageView * bgImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 270)];
        bgImage.image = ImageName(@"img_user_bg");
        [heardView addSubview:bgImage];
        
        bgImage.contentMode = UIViewContentModeScaleToFill;
        
        bgImage.userInteractionEnabled =  YES;
        
        CGFloat imageWide = 50;
        CGFloat gapWide = (WIDTH - 50*4)/5;
        
        NSArray * imageArray;
        
        if ([_isMsgStatus isEqualToString:@"yes"]) {
            
            imageArray = @[@"icon_user_resume",@"icon_user_collection",@"icon_user_wallet",@"icon_user_news"];
            
        }else{
            
            imageArray = @[@"icon_user_resume",@"icon_user_collection",@"icon_user_wallet",@"icon_user_news_pre"];
            
        }
        
        NSArray * titleAttay = @[@"简历",@"收藏",@"钱包",@"消息"];
        
        for (int i = 0; i < 4; i++) {
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(gapWide+gapWide*(i%4)+imageWide*(i % 4), 190+10 *(i/4)+(imageWide+15)*(i/4) , imageWide, imageWide);
            btn.tag = 100 + i;
            btn.userInteractionEnabled = YES;
            [btn setImage:[UIImage imageNamed:imageArray[i]] forState:UIControlStateNormal];
            btn.backgroundColor =[UIColor whiteColor];
            [btn addTarget:self action:@selector(ClassBtnClicks:) forControlEvents:UIControlEventTouchUpInside];
            [bgImage addSubview:btn];
            
            UILabel *label = [[UILabel alloc]init];
            label.center = CGPointMake(btn.center.x, btn.center.y + imageWide / 2.f +10);
            label.bounds = CGRectMake(0, 0, 100, 15);
            label.font = [UIFont systemFontOfSize:14];
            label.textColor = [UIColor blackColor];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = titleAttay[i];
            [bgImage addSubview:label];
        }
        
        isUser
        
        UIImageView * heardImage =[[UIImageView alloc]initWithFrame:CGRectMake(WIDTH/2-30, 64, 60, 60)];
        [heardImage sd_setImageWithURL:[NSURL URLWithString:user.avatar] placeholderImage:[UIImage imageNamed:@"img_default_head"]];
        heardImage.layer.cornerRadius = 30.f;
        heardImage.layer.masksToBounds = YES;
        [heardImage setUserInteractionEnabled:YES];
        [heardImage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory)]];
        
        [bgImage addSubview:heardImage];
        
        NSTextAttachment *attch = [[NSTextAttachment alloc] init];
        NSMutableAttributedString *attri;
         
        if ([user.on_sale isEqualToString:@"yes"]) {
            attch.image = [UIImage imageNamed:@"icon_user_vip"];
        }else{
            attch.image = [UIImage imageNamed:@""];
        }
        
        if (user.user_name) {
            attri = [[NSMutableAttributedString alloc] initWithString:user.user_name];
        }else{
            attri = [[NSMutableAttributedString alloc] initWithString:@"点击登录"];
        }
        
        
        attch.bounds = CGRectMake(0, -6, attch.image.size.width, attch.image.size.height);
        NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
        [attri appendAttributedString:string];
        
        
        UILabel * companyName =[[UILabel alloc]initWithFrame:CGRectMake(0, 130, WIDTH, 30)];
        companyName.textColor = [UIColor whiteColor];
        companyName.textAlignment = NSTextAlignmentCenter;
        companyName.font = [UIFont boldSystemFontOfSize:15];
        companyName.attributedText =attri;
        UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory)];
        [companyName addGestureRecognizer:labelTapGestureRecognizer];
        companyName.userInteractionEnabled = YES;
        
        [bgImage addSubview:companyName];
    }
    
    return heardView;
}
-(void)clickCategory{
        isUser
    if (user.user_id) {
        MyInformationViewController *info = [MyInformationViewController new];
        info.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:info animated:YES];
    }else{
        LoginViewController *login = [LoginViewController new];
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
    }
   
}

-(void)ClassBtnClicks:(UIButton *)sender{
    isUser
    if (!user.user_id) {
//        SHuiMBhudTextTimeStr(@"请先登录");
        LoginViewController *login = [LoginViewController new];
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
        return;
    }
    
    if (sender.tag == 100) {
        MyResumeListViewController *resume = [MyResumeListViewController new];
        resume.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:resume animated:YES];
    }else if (sender.tag == 101){
        MyCollectListViewController * collect = [[MyCollectListViewController alloc]init];
        collect.hidesBottomBarWhenPushed =YES;
        [self.navigationController pushViewController:collect animated:YES];
    }else if (sender.tag == 102){
        MyWalletDetailVC *detail = [MyWalletDetailVC new];
        detail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detail animated:YES];
    }else if (sender.tag == 103){
        MessageVC *message = [MessageVC new];
        message.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:message animated:YES];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    isUser
    if (!user.user_id) {
        LoginViewController *login = [LoginViewController new];
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
        return;
    }
    if (indexPath.section==0) {
        if (indexPath.row == 0) {
            CertificationViewController *certification = [CertificationViewController new];
            certification.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:certification animated:YES];
        }
        
        if (indexPath.row == 1) {
            HRViewController *hr = [HRViewController new];
            hr.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:hr animated:YES];
        }
        
        if (indexPath.row == 2) {
            MyBuyViewController * buy =[MyBuyViewController new];
            buy.hidesBottomBarWhenPushed =YES;
            [self.navigationController pushViewController:buy animated:YES];
            
        }
        
        if (indexPath.row == 3) {
            MyLookListViewController * look =[MyLookListViewController new];
            look.hidesBottomBarWhenPushed =YES;
            [self.navigationController pushViewController:look animated:YES];
        }
        
        if (indexPath.row == 4) {
            MyReceivedViewController *receive = [MyReceivedViewController new];
            receive.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:receive animated:YES];
        }
       
    }else{
        if (indexPath.row == 0) {
            SetViewController *set = [SetViewController new];
            set.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:set animated:YES];
            
        }
    }
    
    
}


#pragma mark -- 未读消息 --
-(void)postDataNoStatus{
    isUser
    NSString *strUrl = [NSString stringWithFormat:post_msgStatus_api];
    
    NSDictionary *dicParameter = @{@"user_id":user.user_id,
                                   @"token":user.token};
    
    [PostNetWorking postNetWorkingStr:strUrl andparameters:dicParameter Success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 200) {
            
            _isMsgStatus = responseObject[@"datas"][@"status"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView reloadData];
                
            });
        }else{
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
        
    } failed:^(NSError *error) {
        
        SHuiMBhudTextTimeStr(@"网络错误");
    }];
}


 
@end
